/*
 * @Description: 新建检测方案 - 检测规则
 * @Author: Rfan
 * @Date: 2022-10-10 11:23:21
 * @LastEditTime: 2022-10-24 18:42:27
 */

import {
  forwardRef,
  MutableRefObject,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from 'react';
import { Tabs } from 'antd';
import cs from 'classnames';
import classnames from 'classnames/bind';
import { isNullObj } from '@/utils';
import { useAddPlanDialogContext } from '../../contexts/AddPlanDialogContext';
import { useArchivesDetectionContext } from '../../../../../contexts/ArchivesDetectionContext';
import { CheckedObjType } from '../../../../../dictionaries';
import EntryPanes from './EntryPanes';
import OriginalPanes from './OriginalPanes';
import EEPPanes from './EEPPanes';
import CDPanes from './CDPanes';
import EnvironmentPanes from './EnvironmentPanes';
import type { IBaseDic } from '@/interfaces/global';
import styles from '../../styles/main.module.scss';

const cx = classnames.bind(styles);

export interface IRefList {
  authenticationRef: MutableRefObject<any>;
  integrityRef: MutableRefObject<any>;
  securityRef: MutableRefObject<any>;
  usabilityRef: MutableRefObject<any>;
}

const CheckRules = ({ type }: { type: number }, ref: any) => {
  const { selectAT } = useArchivesDetectionContext();

  const { showPaneListByType, currentPlanInfo, currentRuleInfo, setDetectionRules, saveRulesFunc } =
    useAddPlanDialogContext();

  const authenticationRef = useRef(null);
  const integrityRef = useRef(null);
  const securityRef = useRef(null);
  const usabilityRef = useRef(null);

  const refList: IRefList = {
    authenticationRef,
    integrityRef,
    securityRef,
    usabilityRef
  };

  /**
   * @description: 收集各属性数据
   * @return {any[]}
   */
  const collectData = () => {
    const auth = authenticationRef.current?.save();
    const integrity = integrityRef.current?.save();
    const security = securityRef.current?.save();
    const usability = usabilityRef.current?.save();
    return [auth, integrity, security, usability].filter((item) => item);
  };

  /**
   * @description: 保存检测规则
   * @param {any} onClose 关闭方法，保存成功后调用
   */
  const saveRules = (onClose: any) => {
    const detectionRuleJson = collectData();

    const { id: archiveTypeId, atCode, atType } = selectAT;
    const params = {
      archiveTypeId,
      atCode,
      atType,
      detectionRuleJson: JSON.stringify(detectionRuleJson),
      schemeId: currentPlanInfo.id
    };
    saveRulesFunc(params).then(() => {
      onClose();
    });
  };

  /**
   * @description: 缓存数据
   */
  const cacheData = () => {
    const detectionRuleJson = JSON.stringify(collectData());
    if (currentRuleInfo && !isNullObj(currentRuleInfo)) {
      setDetectionRules({ ...currentRuleInfo, detectionRuleJson });
    } else {
      const { id: archiveTypeId, atCode, atType } = selectAT;
      const rulesObj = {
        archiveTypeId,
        atCode,
        atType,
        detectionRuleJson,
        schemeId: currentPlanInfo.id
      };
      setDetectionRules(rulesObj);
    }
  };

  // 整理规则逻辑
  useImperativeHandle(ref, () => ({
    saveRules,
    cacheData
  }));

  // 当前选中的tab
  const [paneList, setPaneList] = useState<IBaseDic[]>([]);
  const [currentTab, setCurrentTab] = useState<string>('');

  useEffect(() => {
    if (type) {
      const filteredList: IBaseDic[] = showPaneListByType(type) || [];
      if (filteredList.length) {
        setPaneList(filteredList);
        setCurrentTab(filteredList[0].id + '');
      }
    }
  }, [type]);

  /**
   * @description: tab切换
   * @param {string} key 选中的tab的key
   */
  const tabsChange = (key: string) => {
    setCurrentTab(key);
  };

  return (
    <div className={cs(cx('step-pane'), cx('check-rules'))}>
      <Tabs activeKey={currentTab} onChange={tabsChange}>
        {type === CheckedObjType.Entry && EntryPanes({ paneList, refList })}
        {type === CheckedObjType.Original && OriginalPanes({ paneList, refList })}
        {type === CheckedObjType.EEP && EEPPanes({ paneList, refList })}
        {type === CheckedObjType.CD && CDPanes({ paneList, refList })}
        {type === CheckedObjType.Environment && EnvironmentPanes({ paneList, refList })}
      </Tabs>
    </div>
  );
};

export default forwardRef(CheckRules);
